package org.dromara.system.job;

import com.aizuda.snailjob.client.job.core.annotation.JobExecutor;
import com.aizuda.snailjob.client.job.core.dto.JobArgs;
import com.aizuda.snailjob.client.model.ExecuteResult;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.dromara.system.domain.FirePump;
import org.dromara.system.mapper.FirePumpMapper;
import org.dromara.system.service.ISensorBackUpService;
import org.dromara.system.service.ISensorService;
import org.dromara.system.service.IVariableAssociationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.util.List;

@JobExecutor(name = "getDevicePointJob")
@Slf4j
@Component
@RequiredArgsConstructor(onConstructor_ = @Autowired)
public class getDevicePointJob {

    private static final long SENSOR_ID_BASE = 37688L;
    private static final int SENSOR_COUNT = 3;

    private final FirePumpMapper baseMapper;
    private final IVariableAssociationService variableAssociationService;
    private final ISensorService sensorService;

    private final ISensorBackUpService sensorBackUpService;

    public ExecuteResult jobExecute(JobArgs jobArgs) {
        try {
            List<FirePump> firePumps = baseMapper.selectAllList();
            for (FirePump firePump : firePumps) {
                updateSensorValues(firePump, firePump.getPoint());
            }
            return ExecuteResult.success("更新点位数据成功");
        } catch (Exception e) {
            log.error("执行任务失败", e);
            return ExecuteResult.failure("执行任务失败: " + e.getMessage());
        }
    }

    private void updateSensorValues(FirePump firePump, int point) {
        long sensorIdOffset = (long) (point - 1) * SENSOR_COUNT;
        for (int i = 0; i < SENSOR_COUNT; i++) {
            long sensorId = SENSOR_ID_BASE + sensorIdOffset + i;
            BigDecimal channelData = getChannelData(firePump, i);
            variableAssociationService.updateDeviceStatus(sensorId);//更新设备状态
            variableAssociationService.updatePointSensorValue(sensorId, channelData);
            BigDecimal lastValue = sensorService.getLatestData(sensorId);
            if (lastValue == null || channelData.compareTo(lastValue) != 0) {
                sensorService.insertPointData(channelData, sensorId);
                //备份
                sensorBackUpService.insertPointData(channelData, sensorId);
            }
        }
    }

    private BigDecimal getChannelData(FirePump firePump, int index) {
        switch (index) {
            case 0:
                return firePump.getChannelData1();
            case 1:
                return firePump.getChannelData2();
            case 2:
                return firePump.getChannelData3();
            default:
                throw new IllegalArgumentException("无效的通道索引: " + index);
        }
    }
}
